#!usr/bin/env python  
#@time: 2018/01/22
#分布式演示
#如果出现报错 _pickle.PicklingError: Can't pickle <function <lambda> at 0x006B46F0>: attribute lookup <lambda> on __main__ failed
#请关闭防火墙
import random, time, queue
from multiprocessing.managers import BaseManager

#发送任务的队列
send_task_queue = queue.Queue()
#接收结果的队列
receive_result_queue = queue.Queue()

#从BaseManager继承QueueManager
class QueueManager(BaseManager):
    pass

if __name__ == '__main__':
    #把两个Queue都注册到网络上,callable参数关联了Queue对象
    QueueManager.register('get_task_queue', callable=lambda: send_task_queue)
    QueueManager.register('get_result_queue', callable=lambda: receive_result_queue)

    #绑定端口5000，设置验证码'qwe123'
    manager = QueueManager(address=('',5000),authkey=b'qwe123')
    #启动queue
    manager.start()
    #获得通过网络访问的Queue对象
    task = manager.get_task_queue()
    result = manager.get_result_queue()

    #加入几个任务进去
    for i in range(10):
        n = random.randint(0,10000)
        print('加入任务 %d ...' %n)
        task.put(n)

    #从接收队列中 读取结果
    print('获取结果中...')
    for i in range(10):
        r = result.get(timeout = 10)
        print('接收到的结果: %s' %r)

    #关闭
    manager.shutdown()
    print('主进程退出')

